<template>
  <div class="profile-settings">
    <h2 class="profile-settings__title">个人资料</h2>
    <p class="profile-settings__subtitle">管理您的账户个人信息和头像。</p>

    <div class="settings-card">
      <div class="settings-card__body">
        <!-- 头像上传区域 -->
        <!-- <div class="settings-section">
          <h3 class="settings-section__title">头像</h3>

          <div class="avatar-uploader">
            <div class="avatar-preview" @click="triggerFileUpload">
              <img v-if="previewImage || avatar" :src="previewImage || avatar" alt="用户头像" class="avatar-image" />
              <div v-else class="avatar-placeholder">
                <i class="fas fa-user"></i>
              </div>

              <div class="avatar-overlay">
                <i class="fas fa-camera"></i>
                <span>更换头像</span>
              </div>
            </div>

            <input type="file" ref="fileInput" accept="image/*" style="display: none" @change="handleFileChange" />

            <div class="avatar-actions">
              <button class="btn btn-outline btn-sm" @click="triggerFileUpload">
                <i class="fas fa-upload"></i> 上传新头像
              </button>
              <button v-if="previewImage || avatar" class="btn btn-outline btn-sm btn-danger" @click="removeAvatar">
                <i class="fas fa-trash-alt"></i> 移除
              </button>
            </div>

            <p class="avatar-tips">支持JPG、PNG、GIF格式，大小不超过2MB</p>
          </div>
        </div> -->

        <!-- 基本信息表单 -->
        <div class="settings-section">
          <h3 class="settings-section__title">基本信息</h3>

          <div class="form-group">
            <label class="form-label">姓名</label>
            <input type="text" class="form-control" placeholder="请输入您的姓名" v-model="userData.user_name" disabled />
          </div>

          <div class="form-group">
            <label class="form-label">联系电话</label>
            <input type="tel" class="form-control" placeholder="请输入您的联系电话" v-model="userData.phone" disabled />
          </div>

          <div class="form-group">
            <label class="form-label">地址</label>
            <input type="tel" class="form-control" placeholder="请输入您的地址" v-model="userData.address" />
          </div>

          <div class="form-group">
            <label class="form-label">电子邮件</label>
            <input type="email" class="form-control" placeholder="请输入您的电子邮件" v-model="userData.email" disabled />
            <div class="form-help">电子邮件地址是您的账户登录凭证，无法修改</div>
          </div>

          <div class="form-group">
            <label class="form-label">个人简介</label>
            <textarea class="form-control" placeholder="请输入个人简介" v-model="userData.remarks" disabled
              rows="4"></textarea>
            <div class="form-help">简短描述一下您自己，最多300字（{{ bio.length }}/300）</div>
          </div>
        </div>
      </div>

      <div class="settings-card__footer">
        <button class="btn btn-primary" :disabled="isSaving" @click="onSubmit">
          <span v-if="isSaving">
            <i class="fas fa-circle-notch fa-spin"></i> 保存中...
          </span>
          <span v-else>
            <i class="fas fa-save"></i> 保存更改
          </span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue'
import { GetAgentUserInfoApi, SerUserDataEdit } from '@/api/index'
import { ElMessage } from 'element-plus'

// 表单数据
const name = ref('')
const phone = ref('')
const email = ref('')
const bio = ref('')
const avatar = ref('')
const previewImage = ref('')

// 文件上传
const fileInput = ref<HTMLInputElement | null>(null)

// 状态
const isSaving = ref(false)

// 初始化数据
onMounted(async () => {
  try {
    // 模拟从API获取数据
    await new Promise(resolve => setTimeout(resolve, 600))

    // 模拟后端返回的数据
    const data = {
      name: '张三',
      phone: '13800138000',
      email: 'distributor@example.com',
      bio: '我是一名专业的食品经销商，专注于高品质食品的分销服务。拥有5年食品配送经验，与多家餐厅建立了良好的合作关系。',
      avatar: 'https://randomuser.me/api/portraits/men/1.jpg'
    }

    // 更新本地状态
    name.value = data.name
    phone.value = data.phone
    email.value = data.email
    bio.value = data.bio
    avatar.value = data.avatar
  } catch (error) {
    console.error('加载个人资料失败', error)
  }
})

// 方法
const triggerFileUpload = () => {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files[0]) {
    const file = input.files[0]

    // 检查文件大小
    if (file.size > 2 * 1024 * 1024) {
      alert('图片大小不能超过2MB')
      return
    }

    // 检查文件类型
    if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
      alert('只支持JPG、PNG、GIF格式的图片')
      return
    }

    // 创建预览
    const reader = new FileReader()
    reader.onload = e => {
      if (e.target) {
        previewImage.value = e.target.result as string
      }
    }
    reader.readAsDataURL(file)
  }
}

const removeAvatar = () => {
  previewImage.value = ''
  avatar.value = ''
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

const saveProfile = async () => {
  if (isSaving.value) return

  isSaving.value = true

  try {
    // 构建提交的数据
    const profileData = {
      name: name.value,
      phone: phone.value,
      email: email.value,
      bio: bio.value,
      avatar: previewImage.value || avatar.value,
    }

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 800))
    console.log('保存的个人资料:', profileData)

    // 更新avatar，将previewImage的值赋给avatar
    if (previewImage.value) {
      avatar.value = previewImage.value
      previewImage.value = ''
    }

    // 成功提示
    alert('个人资料已保存')
  } catch (error) {
    console.error('保存个人资料失败', error)
    alert('保存失败，请重试')
  } finally {
    isSaving.value = false
  }
}

// --------------------------
const userData = reactive({
  id: '',
  user_name: '',
  phone: '',
  address: '',
  email: '',
  remarks: '',
})

const getUserInfoRequest = async () => {
  try {
    const res = await GetAgentUserInfoApi({})

    userData.id = res.data.id
    userData.user_name = res.data.user_name
    userData.phone = res.data.phone
    userData.address = res.data.address
    userData.email = res.data.email
    userData.remarks = res.data.remarks

  } catch (error) {
    console.log(error);

  }
}

getUserInfoRequest()

const onSubmit = async () => {
  try {
    const res = await SerUserDataEdit(userData)

    ElMessage({
      type: 'success',
      message: '保存成功!'
    })
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '保存失败!'
    })
  }
}
</script>

<style scoped lang="scss">
.profile-settings {
  margin-bottom: 32px;

  &__title {
    font-size: 20px;
    font-weight: 600;
    color: #2F3542;
    margin-top: 0;
    margin-bottom: 8px;
  }

  &__subtitle {
    color: #6C757D;
    margin-bottom: 24px;
  }
}

.settings-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;

  &__body {
    padding: 24px;
  }

  &__footer {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
    display: flex;
    justify-content: flex-end;
  }
}

.settings-section {
  margin-bottom: 32px;

  &:last-child {
    margin-bottom: 0;
  }

  &__title {
    font-size: 16px;
    font-weight: 600;
    margin-top: 0;
    margin-bottom: 16px;
    color: #2F3542;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
  }
}

// 头像上传区域
.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 24px;

  @media (min-width: 768px) {
    flex-direction: row;
    align-items: flex-start;
  }
}

.avatar-preview {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
  border: 2px solid #f0f0f0;
  cursor: pointer;
  margin-bottom: 16px;

  @media (min-width: 768px) {
    margin-bottom: 0;
    margin-right: 24px;
  }

  &:hover .avatar-overlay {
    opacity: 1;
  }
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background-color: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;

  i {
    font-size: 48px;
    color: #adb5bd;
  }
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
  color: white;

  i {
    font-size: 24px;
    margin-bottom: 8px;
  }

  span {
    font-size: 12px;
  }
}

.avatar-actions {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;

  @media (min-width: 768px) {
    flex-direction: column;
  }
}

.avatar-tips {
  font-size: 12px;
  color: #6C757D;
  margin-top: 8px;

  @media (min-width: 768px) {
    margin-top: 12px;
  }
}

// 表单样式
.form-group {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
}

.form-control {
  width: 100%;
  padding: 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s;

  &:focus {
    outline: none;
    border-color: #FF4757;
    box-shadow: 0 0 0 2px rgba(255, 71, 87, 0.1);
  }

  &:disabled {
    background-color: #f8f9fa;
    cursor: not-allowed;
  }

  &::placeholder {
    color: #adb5bd;
  }
}

textarea.form-control {
  resize: vertical;
  min-height: 100px;
}

.form-help {
  margin-top: 6px;
  font-size: 12px;
  color: #6C757D;
}

// 按钮样式
.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 10px 16px;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;

  i {
    margin-right: 8px;
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }

  &.btn-sm {
    padding: 6px 12px;
    font-size: 13px;
  }

  &.btn-primary {
    background-color: #FF4757;
    color: white;

    &:hover:not(:disabled) {
      background-color: darken(#FF4757, 5%);
    }
  }

  &.btn-outline {
    background-color: transparent;
    border: 1px solid #ced4da;
    color: #495057;

    &:hover:not(:disabled) {
      background-color: #f8f9fa;
    }

    &.btn-danger {
      border-color: #dc3545;
      color: #dc3545;

      &:hover:not(:disabled) {
        background-color: rgba(220, 53, 69, 0.1);
      }
    }
  }
}

@media (max-width: 768px) {
  .settings-card {
    &__body {
      padding: 16px;
    }

    &__footer {
      padding: 12px 16px;
    }
  }

  .btn {
    width: 100%;
  }
}
</style>
